<?php

namespace Modules\Admin\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\Common\StatusData;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class AdminAuth
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $auth = Auth()->guard('admin');
        try {
            if(!$auth->check()){
              return  response()->json([
                    'status'  => StatusData::ACCESS_TOKEN_TIMEOUT,
                    'message' => '请登录!',
                    'data' => []
                ]);
            }
        }catch (TokenExpiredException $e){
            return  response()->json([
                'status'  => StatusData::ACCESS_TOKEN_TIMEOUT,
                'message' => $e->getMessage(),
                'data' => []
            ]);
        }catch (TokenInvalidException $e){
          return response()->json([
              'status'  => StatusData::INVALID,
              'message' => $e->getMessage(),
              'data' => []
          ]);
        }catch (JWTException $e){
            return response()->json([
                'status'  => StatusData::INVALID,
                'message' => $e->getMessage(),
                'data' => []
            ]);
        }
        return $next($request);
    }
}
